<template>
  <div v-loading="isLoading" element-loading-text="加载中...">
    <ElTreeV2
      :key="uuid"
      ref="treeRef"
      v-bind="getBindValue"
      :height="treeHegith"
      :expand-on-click-node="false"
      :filter-method="filterMethod"
    >
      <template #default="{ node, data }">
        <ElementTreeLine
          :node="node"
          :treeData="getBindValue.data"
          :props="getBindValue.props"
          :showLabelLine="false"
          :indent="16"
        >
          <div class="flex items-center flex-1">
            <slot name="recordIconSlot" v-bind="data"></slot>

            <!-- 
          <template v-if="data.type == 1 || data.type == 10">
            <icon-font v-if="!data.expanded" icon="xiangmudaohang" color="#FEA43A" class="flex-shrink-0" />
            <icon-font v-else icon="xiangmudaohang" color="#FEA43A" class="flex-shrink-0" />
          </template>
          <template v-else-if="data.type == 2">
            <icon-font icon="up" color="rgba(13,157,87,0.5)" class="flex-shrink-0" />
          </template>
          <template v-else>
            <icon-font icon="up" color="rgba(52,94,187,0.5)" class="flex-shrink-0" />
          </template> -->
            <ElTooltip
              :visible="tooltipVis && tooltipKey == data.key"
              :content="data.title"
              placement="top"
            >
              <span
                class="mt-[2px] pp text-[14px] z-20"
                @mouseenter="hadnleMouse($event, data.key)"
                @mouseleave="hadnleLeave"
                @dblclick="hadnledbClick(data)"
              >
                <slot name="title" v-bind="data">
                  {{ data.title }}
                </slot>
              </span>
            </ElTooltip>
            <slot name="rightBtn" v-bind="data"></slot>
          </div>
        </ElementTreeLine>
      </template>

      <template #empty>
        <div class="flex items-center justify-center" :style="'height:' + treeHegith + 'px'">
          <ElEmpty />
        </div>
      </template>
    </ElTreeV2>
  </div>
</template>
<script lang="ts" setup>
import { getElementLabelLine } from 'element-tree-line';
import { ElTreeV2, ElEmpty, ElTooltip } from 'element-plus';
import { computed, h, ref, unref, useAttrs } from 'vue';
import { treeProps } from './props';
import { isBeyond } from './hooks/utls';
import type { SzTreePropsType, TreeMethods } from './types/treeType';
import { buildUUID, deepMerge } from '#/utils/gloab';
import type { Recordable } from '#/types/global';
import type { TreeKey, TreeNodeData } from 'element-plus/es/components/tree-v2/src/types';
const isLoading = ref<boolean>(false);
let uuid = ref<string>(buildUUID());
const ElementTreeLine = getElementLabelLine(h);
const emit = defineEmits(['register', 'dbClick']);
const tooltipVis = ref<boolean>(true);
let tooltipKey = ref<string>('');
const treeRef = ref<any>(null);
const propsRef = ref<Partial<any> | null>(null);
let selectedKeys = ref<string[] | number[]>();
let attr = useAttrs();
let props = defineProps(treeProps);
let treeHegith = ref<number>(500);
let getBindValue = computed(() => {
  const valued = {
    ...attr,
    ...props,
    ...unref(propsRef),
    // icon: () => {
    //   // console.log('eee', e);
    //   return h(CaretRight, { size: 40 });
    // }
  };
  // console.log('valued', valued);
  return valued;
});
let getTreeRef = computed(() => {
  return treeRef.value ? treeRef.value : null;
});
const treeMethods: TreeMethods = {
  setTreeProps,
  treesCrollTo,
  setLoading,
  getTreeRef,
  setCheckedKeys,
  getCheckedNodes,
};
// 若节点可被选择（即show-checkbox为 true），则返回目前被选中的节点所组成的数组
function getCheckedNodes(leafOnly: boolean) {
  return treeRef.value?.getCheckedNodes(leafOnly);
}
function setTreeProps(props: SzTreePropsType): void {
  // console.log('props', props);
  propsRef.value = deepMerge(unref(propsRef) || ({} as any), props);
  if (Reflect.has(props, 'expandedKeys')) {
    // console.log('expandedKeys', props.expandedKeys);
    const time = setTimeout(() => {
      treeRef.value.setExpandedKeys(props.expandedKeys);
      clearTimeout(time);
    }, 20);
  }
  if (Reflect.has(props, 'treeHegith')) {
    treeHegith.value = props.treeHegith!;
  }
  if (Reflect.has(props, 'treeData')) {
    // console.log('treeRef.value', treeRef.value);
    treeRef.value.setData(props.treeData);
  }
  if (Reflect.has(props, 'currentKey')) {
    treeRef.value.setCurrentKey(props.currentKey);
  }
  if (Reflect.has(props, 'filterText')) {
    treeRef.value.filter(props.filterText);
  }
}
// 通过 keys 设置目前勾选的节点
function setCheckedKeys(keys: TreeKey[]) {
  treeRef.value?.setCheckedKeys(keys);
}
function setLoading(bool: boolean) {
  isLoading.value = bool;
}
const filterMethod = (query: string, node: TreeNodeData) => node.title!.includes(query);

function hadnleMouse(e: Event, key: string) {
  tooltipVis.value = isBeyond(e);
  tooltipKey.value = key;
}
function hadnleLeave() {
  tooltipVis.value = false;
  tooltipKey.value = '';
}
function treesCrollTo() {
  let time = setTimeout(() => {
    treeRef.value?.scrollTo({
      key: (selectedKeys.value as string[])[0],
      align: 'auto',
    });
    clearTimeout(time);
  }, 100);
}
function hadnledbClick(data: Recordable) {
  console.log('双击事件', data);
  // emit('dbClick', data);
}

emit('register', treeMethods);
</script>
<style lang="scss">
.el-tree-node__content > .el-tree-node__expand-icon {
  // background-color: red;
  width: 1.8em;
  height: 1.8em;
}

.tree-first-data {
  // background-color: red;
  .element-tree-node-line-ver {
    display: none !important;
  }
  .element-tree-node-line-hor {
    display: none !important;
  }
}
</style>

<style lang="scss" scoped>
.pp {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  display: -webkit-box;
  line-clamp: 1;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
</style>
